<template>
  <div>
    <div class="topcontainer">
      <h4>已排序字段</h4>
    </div>

    <el-table
      :data="tableFieldLst"
      :row-style="{height:'30px'}"
      :cell-style="{padding:'0px'}"
      style="width: 100%;font-size: 10px"
      class="table"
      height="calc(100vh - 270px)"
    >
      <el-table-column prop="tableName" label="表名称" align="center">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.isDefault">{{ scope.row.tableName }}</span>
            <el-select
              v-else
              placeholder
              v-model="scope.row.tableId"
              @change="changeforeignTableId"
            >
              <el-option
                v-for="item in searchList"
                :key="item.tableId"
                :label="item.tableName"
                :value="item.tableId"
              >{{ item.tableName }}</el-option>
            </el-select>
            <!-- searchList -->
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="tableId"
        label="表id"
        align="center"
      ></el-table-column>-->
      <!-- <el-table-column
        prop="fieldName"
        label="字段名称"
        align="center"
      ></el-table-column>-->
      <el-table-column prop="fieldName" label="字段名称" align="center">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.isDefault">{{ scope.row.fieldName }}</span>
            <el-select
              v-else
              placeholder
              v-model="scope.row.fieldId"
              :disabled="!scope.row.tableId"
              @change="changeField($event, scope.$index)"
            >
              <el-option
                v-for="item in foreignFieldList"
                :key="item.fieldId"
                :label="item.fieldName"
                :value="item.fieldId"
              >{{ item.fieldName }}</el-option>
            </el-select>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="fieldId"
        label="字段名称id"
        align="center"
      ></el-table-column>-->
      <el-table-column prop="seqNo" label="顺序号" align="center"></el-table-column>
      <el-table-column prop="sortType" label="过滤类型" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.isDefault">
            {{
            scope.row.sortType | capitalize
            }}
          </span>
          <el-select
            v-else
            placeholder
            v-model="scope.row.sortType"
            @change="changeType($event, scope.$index)"
          >
            <el-option
              v-for="line in options"
              :key="line.value"
              :label="line.lable"
              :value="line.value"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column prop="tableId" label="操作" align="center">
        <template slot-scope="scope">
          <el-button @click="delTable(scope)" type="text" v-if="scope.row.isDefault">删除</el-button>
          <el-button @click="cancleJoin" type="text" v-else>取消</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="btn">
      <el-button type="primary" @click="addJoin" size="mini">添加关联</el-button>
      <el-button type="primary" @click="submitJoin" v-if="isAdd" size="mini">确定</el-button>
      <!-- <el-button type="primary" @click="cancleJoin" v-if="isAdd" size="mini"
        >取消</el-button
      >-->
    </div>
  </div>
</template>
<script>
import { jsonClone } from "../components/utils";
import { api } from "../server/api";
export default {
  data() {
    return {
      tableId: "",
      tableFieldLst: [],
      dialogVisible: false,
      searchList: [],
      tableData: [],
      foreignFieldList: [],
      allSelect: {},
      isAdd: false,
      queryParams: {
        tableId: ""
      },
      options: [
        { lable: "升序", value: 0 },
        { lable: "降序", value: 1 }
      ]
    };
  },

  filters: {
    capitalize: function(value) {
      let list = [
        { lable: "升序", type: 0 },
        { lable: "降序", type: 1 }
      ];
      let findvalue = list.find(val => {
        return val.type === value;
      });
      return findvalue.lable;
    }
  },
  created() {
    this.tableId = this.$route.query.tableId;
    this.getDatils();
    this.getsearchList();
  },
  methods: {
    getDatils() {
      let allSelect = {};
      api.stdappTableSortLst(this.tableId).then(res => {
        res.map(item => {
          item.isDefault = true;
        });
        this.tableFieldLst = res;
      });
    },
    //获取除了当前表其他表的list
    getsearchList() {
      api.stdappTableJoinLst(this.tableId).then(res => {
        this.searchList = [
          { tableId: this.tableId, tableName: this.$route.query.name }
        ];
        let obj = {};
        res.map(item => {
          obj = {
            tableId: item.foreignTableId,
            tableName: item.foreignTableName
          };
          this.searchList.push(obj);
        });
      });
    },
    //新增关联
    addJoin() {
      this.tableFieldLst.push({ isDefault: false, sortType: 0 });
      this.isAdd = true;
    },
    submitJoin() {
      for (let index = 0; index < this.tableFieldLst.length; index++) {
        const element = this.tableFieldLst[index];
        const { tableId, fieldId, seqNo, sortType } = element;
        console.log(tableId, fieldId, seqNo);
        if (!tableId || !fieldId || !seqNo) {
          this.$message.warning("请选择");
          return;
        }
      }
      this.submit();
    },
    cancleJoin() {
      // this.isAdd = false;
      this.tableFieldLst.pop();
      if (this.tableFieldLst.length == 0) {
        this.isAdd = false;
      }
    },
    delTable(scope) {
      console.log(scope.$index);
      this.tableFieldLst.splice(scope.$index, 1);
      this.submit();
    },
    changeforeignTableId(e) {
      console.log(e);
      this.foreignFieldList = [];
      this.getForeignFieldList(e);
    },
    getForeignFieldList(e) {
      api.stdappTableDetail({ tableId: e }).then(res => {
        console.log(res);
        let { fieldLst } = res;
        let arr = fieldLst.filter(item => {
          return (
            item.fieldType == "InputNumber" ||
            item.fieldType == "InputText" ||
            item.fieldType == "InputDate" ||
            item.fieldType == "IdentityKey" ||
            item.fieldType == "RadioBox" ||
            item.fieldType == "Checkbox" ||
            item.fieldType == "SelectRadio" ||
            item.fieldType == "SelectCheck"
          );
        });
        console.log(arr);
        this.foreignFieldList = arr;
      });
    },
    changeField(e, index) {
      console.log(e);
      let data = this.foreignFieldList.find(item => {
        return item.fieldId == e;
      });
      this.$set(this.tableFieldLst[index], "seqNo", data.seqNo);
      console.log(this.tableFieldLst);
    },
    changeType(e, index) {
      console.log(index);
      this.$set(this.tableFieldLst[index], "sortType", e);
      console.log(this.tableFieldLst);
    },
    submit() {
      let arr = [];
      for (let index = 0; index < this.tableFieldLst.length; index++) {
        const element = this.tableFieldLst[index];
        const { tableId, fieldId, seqNo, sortType } = element;
        const obj = { tableId, fieldId, seqNo, sortType };
        if (tableId && fieldId && seqNo) {
          arr.push(obj);
        }
      }
      const data = {
        tableId: this.tableId,
        pairLst: arr
      };
      console.log(data);
      api.stdappTableSetSort(data).then(res => {
        this.multipleSelection = [];
        this.$message.success("排序成功");
        this.dialogVisible = false;
        this.isAdd = false;
        this.allSelect = {};
        this.getDatils();
      });
    }
    // handleSelectionChange(row) {
    //   const { tableId } = this.queryParams;
    //   this.multipleSelection = row;
    //   console.log(row);
    //   this.$nextTick(() => {
    //     this.$set(this.allSelect, tableId, row);
    //   });
    // },

    // resetQuery() {
    //   this.queryParams = {
    //     tableId: "",
    //   };
    // },
    // joinViceTable() {
    //   this.tableData = [];
    //   this.dialogVisible = true;
    //   let allSelect = {};
    //   for (let index = 0; index < this.tableFieldLst.length; index++) {
    //     const element = this.tableFieldLst[index];
    //     const key = element.tableId;
    //     allSelect[key] = allSelect[key]
    //       ? [...allSelect[key], element]
    //       : [element];
    //   }
    //   this.allSelect = JSON.parse(JSON.stringify(allSelect));
    //   console.log(this.allSelect);
    //   this.$forceUpdate();
    //   setTimeout(() => {
    //     this.getsearchList();
    //   }, 100);
    // },
    // getsearchList() {
    //   api.stdappTbls4Join().then((res) => {
    //     this.searchList = res.filter((item) => {
    //       return item.tableId != this.tableId;
    //     });
    //     this.$set(this.queryParams, "tableId", this.searchList[0].tableId);
    //     this.getFieldList();
    //   });
    // },
    // getFieldList() {
    //   api.stdappTableDetail(this.queryParams).then((res) => {
    //     let { fieldLst } = res;
    //     this.tableData = fieldLst;
    //     let data = JSON.parse(
    //       JSON.stringify(this.allSelect[this.queryParams.tableId])
    //     );
    //     setTimeout(() => {
    //       if (data) {
    //         for (let index = 0; index < data.length; index++) {
    //           const element = data[index];
    //           const val = fieldLst.find((item) => {
    //             return item.fieldId == element.fieldId;
    //           });
    //           this.$refs.multipleTable.toggleRowSelection(val, true);
    //         }
    //       } else {
    //         this.$refs.multipleTable.clearSelection();
    //       }
    //     }, 100);
    //   });
    // },
    // submitJoin(sortType) {
    //   const arr = [];
    //   for (let key in this.allSelect) {
    //     console.log(this.allSelect[key]);
    //     const fieldLst = this.allSelect[key];
    //     for (let index = 0; index < fieldLst.length; index++) {
    //       const element = fieldLst[index];
    //       const obj = {
    //         seqNo: element.seqNo,
    //         tableId: key,
    //         fieldId: element.fieldId,
    //         sortType,
    //       };
    //       arr.push(obj);
    //     }
    //   }
    //   console.log(arr);
    //   const data = {
    //     tableId: this.tableId,
    //     pairLst: arr,
    //   };
    //   api.stdappTableSetSort(data).then((res) => {
    //     this.multipleSelection = [];
    //     this.$message.success("排序成功");
    //     this.dialogVisible = false;
    //     this.allSelect = {};
    //     this.getDatils();
    //   });
    // },
  }
};
</script>
<style lang="scss" scoped>
.topcontainer {
  display: flex;
  height: 60px;
  align-items: center;
  h4 {
    margin: 0 10px;
  }
}
.list {
  .title {
    display: inline-block;
    padding: 5px 0;
  }
  .el-tag {
    margin: 5px;
  }
}
.btn {
  display: flex;
  width: 100vw;
  align-items: center;
  justify-content: center;
  height: 50px;
  .el-button {
    height: 32px;
  }
}
</style>